<?php

namespace App\Jobs;

use App\Exceptions\ApiException;
use App\Models\Live;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Http\service\XcxService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class LiveUpdateJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $start=0;
        $total_page=0;
        $res=(new XcxService())->get_live();
        if($res["errcode"]==0){

            $total=$res["total"];
            if ($total>0){
                $this->insert_sql($res["room_info"]);
            }

            if ($total>100){
                $mod=$total%100;
                $total_page=($total-$mod)/100;
                if ($mod>0){
                    $total_page++;
                    for ($start=1;$start<$total_page;$start++){
                        $res=(new XcxService())->get_live($start);
                        if ($res["errcode"]==0){
                            $this->insert_sql($res["room_info"]);
                        }
                    }
                }

            }
        }else{
            throw new ApiException($res["errmsg"]);
        }
    }

    private function insert_sql($data)
    {
        $model=new Live();
        DB::beginTransaction();
        Log::error($data);
        try {
            foreach ($data as $key=>$value){
                $live=$model->where("roomid",$value["roomid"])->first();
                if (!$live){
                    $model->create($value);
                }else{
                    $model->where("id",$live["id"])->update($value);
                }
            }
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            Log::error($exception);
        }
    }
}
